package com.esunrising.esungsc.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.esunrising.esungsc.common.utils.ESUNGSCUtil;
import com.esunrising.esungsc.common.utils.HttpUtil;
import com.esunrising.esungsc.config.GSCAPIConfig;
import com.esunrising.esungsc.dao.CustomItemsDao;
import com.esunrising.esungsc.entity.TApiXm;
import com.esunrising.esungsc.service.CustomItemsService;
import com.esunrising.esungsc.service.GSCService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class CustomItemsServiceImpl extends BaseServiceImpl<CustomItemsDao, TApiXm> implements CustomItemsService {


    @Resource
    private GSCAPIConfig gscapiConfig;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private GSCService gscService;

    @Resource
    private CustomItemsService customItemsService;

    @Resource
    private CustomItemsDao customItemsDao;

    @Override
    public List<TApiXm> getCustomItemsResult(String date, String enddate, String hszzid, String year, String dwbh, String orgCode) {

        /*
        思路：
         1、向文档中取数据
            1.1拼出请求的url及请求头、请求体
            1.2请求调用indexController，该接口从文件存放位置取数据
         2、将数据进行分解，获取最想要的部分
         3、将要得到的数据进行存储
         */

        String orgId = "";
        String ledger = "";
        String type = "pz-test";

        String url = gscapiConfig.getBaseUrl();
        String s = gscapiConfig.getApis().get("getBFCustomItems");
        String  uri = url + s;

        String queryParam = HttpUtil.putQueryParam(uri, null);

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.addAll(new LinkedMultiValueMap<>(gscapiConfig.getRequestHeaders()));

        HashMap<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("date", date);
        bodyMap.put("enddate", enddate);
        bodyMap.put("hszzid", hszzid);
        bodyMap.put("year", year);

        //组织参数
        HttpEntity<HashMap<String, Object>> httpEntity = new HttpEntity<>(bodyMap, httpHeaders);

        //发送请求
        ResponseEntity<String> response = restTemplate.exchange(queryParam, HttpMethod.POST, httpEntity, String.class);

        String msg = " ";
        if (response.getStatusCodeValue() ==200){
            String body = response.getBody();

            msg = "接口调用成功";

            // 记录日志
            gscService.saveLog(dwbh, orgId, orgCode, ledger, type, msg);
            // 更新调用时间记录
            gscService.updateSyncTime(dwbh, orgId, orgCode, ledger, type, LocalDateTime.now());

            return ParseBFCustomItems(body);
        }else {
            msg = "接口调用失败";

            // 记录日志
            gscService.saveLog(dwbh, orgId, orgCode, ledger, type, msg);

            System.out.println(response.getStatusCodeValue());
            System.out.println(response.getStatusCode());
            System.out.println(response.getHeaders());
            System.out.println(response.getBody());
            return null;
        }

    }

    @Override
    public void saveCustomItemsResult(List<TApiXm> tApiXmList) {
        for (TApiXm tApiXm : tApiXmList){
            customItemsService.syncSave(tApiXm);
        }
    }

    @Override
    public void syncSave(TApiXm tApiXm) {
        Optional<TApiXm> byId = customItemsDao.findById(tApiXm.getId());
        byId.ifPresent(doc ->{
            customItemsDao.deleteById(tApiXm.getId());
        });

        //保存数据
        super.save(tApiXm);
    }

    private List<TApiXm> ParseBFCustomItems(String body) {

        JSONObject jsonObject = JSONObject.parseObject(body);
        Boolean result = jsonObject.getBoolean("result");
        String code = jsonObject.getString("code");
        if (result){
            log.info("获取数据成功");
            JSONArray value = jsonObject.getJSONArray("value");
            List<TApiXm> tApiXmList = new ArrayList<>();
            for (int i = 0; i < value.size(); i++) {
                JSONObject element = value.getJSONObject(i);
                TApiXm tApiXm = ESUNGSCUtil.jsonObject2ApiXm(element);

                tApiXmList.add(tApiXm);
            }
            return tApiXmList;
        }else {
            log.error("请求数据失败");
            return null;
        }

    }

}
